<template>
    <div class="card-wrap animate-on-enter">
        <DataList ref="DataListRef" :api="(params) => getListByPage(params)" :columns="tableColumns">
            <template #status="{ record }">
                <a-switch 
                    :checked="record.status == 1" 
                    @change="(checked) => handleStatusChange(record, checked)"
                    checked-children="正常" 
                    un-checked-children="禁用"
                />
            </template>
        </DataList>
    </div>
</template>

<script setup>
import { ref, h } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { getUsers, toggleUserStatus, getListByPage } from '@/api/user.js';
import DataList from '@/components/DataList.vue';

/**
 * 页面全局变量
 */
const tableColumns = [
    {
        title: '昵称',
        dataIndex: 'nickname'
    },
    {
        title: '用户名',
        dataIndex: 'username',
    },   
    {
        title: '邮箱',
        dataIndex: 'email',
        customRender: ({ record }) => {
            return record.email || '-';
        }
    },
    {
        title: '性别',
        dataIndex: 'gender',
        customRender: ({ record }) => {
            const genderMap = { 0: '未知', 1: '男', 2: '女' };
            return genderMap[record.gender] || '未知';
        }
    },
    {
        title: '登录方式',
        dataIndex: 'login_type',
        customRender: ({ record }) => {
            const typeMap = {
                'username': '用户名密码',
                'wechat': '微信小程序',
                'wechat_mp': '微信公众号'
            };
            return typeMap[record.login_type] || record.login_type;
        }
    },
    {
        title: '状态',
        dataIndex: 'status',
        slot: true,
        align: 'center'
    },
    {
        title: '最后登录时间',
        dataIndex: 'last_login_time',
        customRender: ({ record }) => {
            return record.last_login_time || '-';
        }
    },
    {
        title: '创建时间',
        dataIndex: 'created_at'
    }
];

const DataListRef = ref();

// 处理状态切换
function handleStatusChange(record, checked) {
    const newStatus = checked ? 1 : 0;
    const actionText = checked ? '启用' : '禁用';
    
    Modal.confirm({
        title: '确认操作',
        content: `确定要${actionText}「${record.nickname}」吗？`,
        onOk: async () => {
            try {
                const result = await toggleUserStatus({
                    id: record.id,
                    status: newStatus
                });
                
                if (result.code === 200) {
                    message.success(result.message);
                    DataListRef.value.refreshData();
                } else {
                    message.error(result.message || '操作失败');
                }
            } catch (error) {
                message.error('操作失败');
            }
        }
    });
}
</script>

<style lang="less" scoped>
</style>